<?php

include_once '../Exceptions/CommunicationException.php';
include_once '../InfoManager/InfoAuto.php';
include_once '../InfoManager/InfoZtl.php';
include_once '../Model/GateZtl.php';
include_once '../Model/Location.php';
include_once '../Model/Address.php';
include_once '../Model/GPS.php';


$ia = new InfoAuto();
$iz = new InfoZtl();
$kml_google="";

//La richiesta del Client contiene:
//Lat e Long del punto di Partenza e 
//l'indirizzo del punto d'arrivo

if ((isset($_GET["saddr"])) && (isset($_GET["daddr"])) )
{
	$saddr = (RMobUtils::escape_var($_GET["saddr"]));//echo $saddr.'<br>';
	$address = (RMobUtils::escape_var($_GET["daddr"]));//echo $address.'<br>';
	$sep=",";
	$coord=explode($sep,$saddr);
	$lat = $coord[0];
	$long = $coord[1];

/*
if ((isset($_GET["lat"])) && (isset($_GET["long"])) && (isset($_GET["daddr"])) )
{
	$lat = floatval(RMobUtils::escape_var($_GET["lat"]));
	$long = floatval(RMobUtils::escape_var($_GET["long"]));
	$address = (RMobUtils::escape_var($_GET["address"]));
*/	
	//costruisco l'URL
	$URL = $ia->URL_google($lat, $long, $address);
	//echo $URL.'<br>';
	
	//carico il file KML
	$html = new simple_html_dom($URL);
	
	$xml = $html;
	//echo $html;
	
	//estraggo le coordinate dei geopoint
	$element = $html->find("coordinates");
	
	//estraggo le info sulle strade
	$places = $html->find("Placemark");
	
	//elimino l'ultimo Placemark perchè inutile
	array_pop($places);

	for ($t=0; $t<sizeof($places); $t++){
		$places[$t]=str_replace("&#39;","'",$places[$t]);
		$places[$t]=str_replace("&#160;","",$places[$t]);
		$places[$t]=str_replace("<br/>Map data &#169;2011 Tele Atlas","",$places[$t]);
	}

	//creo l'array di GeoPoint
	$arrayGeoPoint = $ia->CreaGeoPoint($element);
		
	//Carico l'elenco dei Varchi ZTL
	$arrayVarchi = $iz->getGates();
		
	//Creo l'array di varchi presenti sul percorso
	$gates = $ia->FindTheGate($arrayVarchi,$arrayGeoPoint, $places);
		
}

else return null;
$gatexml="";
	if ($gates != NULL)
	{
		try {
			
			foreach ($gates as $gate)
			{
					//extended mode
					$gatexml .= $gate->toXML(EXTENDED_MODE);
			}
		}
		catch (CommunicationException $e)
		{
			echo $e->toXML(EXTENDED_MODE);
			exit(1);
		}
	}
	
	unset($ia);
	unset($iz);
	$stringa = '<?xml version="1.0" encoding="UTF-8"?>';
	$xml = str_replace($stringa,"",$xml);
	$gatexml = "<GATEZTL>".$gatexml."</GATEZTL>";
	$xml = "<XML>"."<KML>".$xml."</KML>".$gatexml."</XML>";
	echo $xml;


?>